<template>
  <div class="auth">
    <div v-if="details.status !== '00100002'" class="header">
      <el-steps :active="step" align-center finish-status="success">
        <el-step title="填写基本信息" />
        <el-step title="上传营业执照" />
        <el-step title="等待审核" />
      </el-steps>
    </div>
    <div v-if="details.status === '00100002'" class="box">
      <el-form
        ref="details"
        :model="details"
        class="details"
        label-width="150px"
        label-position="right"
      >
        <el-form-item class="name" label="公司名称：">{{ details.name }}</el-form-item>
        <el-form-item class="name" label="主营产品：">{{ details.product }}</el-form-item>
        <el-form-item class="name" label="经营地址：">{{ details.address.replace('/', '') }}</el-form-item>
        <el-form-item class="name" label="联系人：">{{ details.contact }}</el-form-item>
        <el-form-item class="name" label="电话：">{{ details.phone }}</el-form-item>
        <el-form-item class="name" label="公司座机：">{{ details.telephone }}</el-form-item>
        <el-form-item class="name" label="统一社会信用代码：">{{ details.code }}</el-form-item>
        <el-form-item class="name" label="营业执照图片">
          <el-image style="width: 150px; height: 210px" :src="qnPath(details.license)" :preview-src-list="srcList" fit="fill" />
        </el-form-item>
        <el-form-item class="name" label="法人：">{{ details.legal }}</el-form-item>
        <el-form-item class="name" label="身份证号：">{{ details.idcard }}</el-form-item>
        <el-form-item class="name" label="身份证正面图片：">
          <el-image style="width: 210px; height: 140px" :src="qnPath(details.front)" :preview-src-list="srcList" fit="fill" />
        </el-form-item>
        <el-form-item class="name" label="身份证反面图片：">
          <el-image style="width: 210px; height: 140px" :src="qnPath(details.verso)" :preview-src-list="srcList" fit="fill" />
        </el-form-item>
      </el-form>
    </div>
    <div v-else class="box">
      <el-form
        v-show="step === 0"
        ref="step1Form"
        class="step step1"
        :model="step1Form"
        :rules="step1FormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item class="name" label="公司名称：" prop="companyName">
          <el-input v-model="step1Form.companyName" clearable class="ipt" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item class="main-pdts" label="主营产品：" prop="product">
          <el-input v-model="step1Form.product" clearable class="ipt" placeholder="请输入主营产品" />
        </el-form-item>
        <el-form-item class="address map" label="经营地址：" prop="address">
          <el-input v-model="step1Form.address" class="ipt" placeholder="请输入详细地址">
            <i slot="prepend" class="el-icon-map-location el-input__icon" @click="mapDialogVisible = true">
              <span>地图定位</span>
            </i>
          </el-input>
        </el-form-item>
        <el-form-item class="contact" label="联系人：" prop="contact">
          <el-input v-model="step1Form.contact" clearable class="ipt" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item class="cellphone" label="电话：" prop="cellphone">
          <el-input v-model="step1Form.cellphone" clearable class="ipt" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item class="telephone" label="公司座机：" prop="telephone">
          <el-input v-model="step1Form.telephone" clearable class="ipt" placeholder="请输入公司座机" />
        </el-form-item>
        <el-form-item class="fixed-margin">
          <el-button type="primary" @click="toStep2('step1Form')">下一步</el-button>
        </el-form-item>
      </el-form>
      <el-form
        v-show="step === 1"
        ref="step2Form"
        class="step step2"
        :model="step2Form"
        :rules="step2FormRules"
        label-width="150px"
      >
        <el-form-item class="credit-code" label="统一社会信用代码：" prop="code">
          <el-input v-model="step2Form.code" clearable class="ipt" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item>
          <el-form-item class="license" label="营业执照：" prop="license">
            <p>请上传三证合一版的新营业执照，若没有请分别上传营业执照、组织机构代码证及税务登记证</p>
            <div class="upload-box licence fixed-margin">
              <div class="img-box">
                <el-image style="width: 100px; height: 130px" :src="qnPath(step2Form.license)" fit="fill" />
              </div>
              <image-upload :size="2048" imgname="营业执照图片" tip="支持.jpg .jpeg .bmp .gif .png格式照片，大小不超过2M" @onSuccess="licencesSuc">
                <el-button icon="el-icon-upload2" size="small">点击上传</el-button>
              </image-upload>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item class="boss" label="法人：" prop="legal">
          <el-input v-model="step2Form.legal" clearable class="ipt" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item class="id" label="身份证号：" prop="idcard">
          <el-input v-model="step2Form.idcard" clearable class="ipt" placeholder="请输入法人身份证号" />
        </el-form-item>
        <el-form-item>
          <el-form-item class="id-pic" label="身份证照片：">
            <p>请上传身份证的正面，反面各一张，支持.jpg .jpeg .bmp .gif .png格式照片，大小不超过2M</p>
            <div class="id-pic-box fixed-margin">
              <div class="upload-box">
                <div class="img-box">
                  <el-image style="width: 120px; height: 80px" :src="qnPath(step2Form.idPic1)" fit="fill" />
                </div>
                <image-upload :size="2048" imgname="身份证正面图片" tip="请上传身份证正面" @onSuccess="idPic1Suc">
                  <el-button icon="el-icon-upload2" size="small">点击上传</el-button>
                </image-upload>
              </div>
              <div class="upload-box">
                <div class="img-box">
                  <el-image style="width: 120px; height: 80px" :src="qnPath(step2Form.idPic2)" fit="fill" />
                </div>
                <image-upload :size="2048" imgname="身份证反面图片" tip="请上传身份证反面" @onSuccess="idPic2Suc">
                  <el-button icon="el-icon-upload2" size="small">点击上传</el-button>
                </image-upload>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item class="fixed-margin">
          <el-button @click="toStep1">上一步</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm('step2Form')">提交</el-button>
        </el-form-item>
      </el-form>
      <div v-show="step === 2" class="step step3">
        <template v-if="details.status === '00100003'">
          <h4>审核失败</h4>
          <p>很抱歉，您的诚信认证未能通过审核，拒绝原因如下：<br><span style="color:rgb(220, 82, 82)">您提交的资料不合规范，请重新提交{{ details.cause }}</span></p>
        </template>
        <template v-if="details.status === '00100001'">
          <h4>提交成功</h4>
          <p>您已成功提交申请诚信认证的相关信息，我们会在3个工作日内进行审核，请您耐心等待</p>
        </template>
      </div>
    </div>

    <!-- 地图弹框 -->
    <el-dialog
      v-el-drag-dialog
      width="60%"
      :visible.sync="mapDialogVisible"
      class="map-dialog"
      center
      @opened="openedMapDialog"
    >
      <h2 slot="title" class="dialog-title">地图定位</h2>
      <p class="dialog-intro">请在地图中定位(<span style="color: #f75757">点击</span>)您的店铺位置，以便于用户更方便的找到您的店铺</p>
      <AMap ref="amap" width="100%" height="55vh" @mapClick="getAddr" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="mapDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import AMap from '@/components/Map';
import ImageUpload from '@/components/ImagesUpload';
import { authCredit, getAuthCredit } from '@/api/user';
import { mapGetters } from 'vuex';
export default {
  name: 'ShopAuthCredit',
  components: { AMap, ImageUpload },
  data() {
    return {
      step: 0,
      loading: false,
      mapDialogVisible: false,
      details: {},
      srcList: [],
      step1Form: {
        companyName: '',
        product: '',
        map: {
          citycode: '',
          country: '',
          province: '',
          city: '',
          district: '',
          township: '',
          street: '',
          streetNumber: '',
          lng: 0,
          lat: 0
        },
        address: '',
        contact: '',
        cellphone: '',
        telephone: ''
      },
      step2Form: {
        code: '',
        license: '',
        legal: '',
        idcard: '',
        idPic1: '',
        idPic2: ''
      },
      step1FormRules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        product: [
          { required: true, message: '请输入主营产品', trigger: 'blur' },
          { min: 2, message: '长度在至少为 2 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入公司详细地址' },
          { min: 2, max: 40, message: '长度在 2 到 40 个字符' }
        ],
        contact: [
          { required: true, message: '请输入法人姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
          { pattern: /^[\u4E00-\u9FA5]+$/, message: '法人姓名只能为中文' }
        ],
        cellphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^1[345789]\d{9}$/.test(value) === false) {
                callback(new Error('请输入正确的手机号'));
              } else {
                callback();
              }
            }
          }
        ]
      },
      step2FormRules: {
        code: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          },
          {
            pattern: /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/,
            message: '统一社会信用代码错误'
          }
        ],
        legal: [
          { required: true, message: '请输入法人姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
          { pattern: /^[\u4E00-\u9FA5]+$/, message: '法人姓名只能为中文' }
        ],
        idcard: [
          { required: true, message: '请输入法人身份证号码', trigger: 'blur' },
          {
            validator: function(rule, idcode, callback) {
              // 加权因子
              const weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
              const check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

              const code = idcode + '';
              const last = idcode[17];

              const seventeen = code.substring(0, 17);

              const arr = seventeen.split('');
              const len = arr.length;
              let num = 0;
              for (let i = 0; i < len; i++) {
                num = num + arr[i] * weight_factor[i];
              }
              const resisue = num % 11;
              const last_no = check_code[resisue];

              const idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

              var format = idcard_patter.test(idcode);
              if (last === last_no && format) {
                callback();
              } else {
                callback(new Error('请输入正确的身份证号码'));
              }
            }
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['shopInfo'])
  },
  beforeMount() {
    this.getAuthCredit();
  },
  methods: {
    openedMapDialog() {
      this.$refs.amap.init();
    },
    next() {
      if (this.step++ > 2) this.step = 0;
    },
    getAddr(addr) {
      this.map = addr;
      this.step1Form.address = addr[0];
      const {
        citycode,
        country,
        province,
        city,
        district,
        township,
        street,
        streetNumber
      } = addr[1];
      this.step1Form.map.citycode = citycode;
      this.step1Form.map.country = country;
      this.step1Form.map.province = province;
      this.step1Form.map.city = city;
      this.step1Form.map.district = district;
      this.step1Form.map.township = township;
      this.step1Form.map.street = street;
      this.step1Form.map.streetNumber = streetNumber;

      this.step1Form.map.lng = addr[2].lng; // 经度
      this.step1Form.map.lat = addr[2].lat; // 纬度
    },
    submitForm(formName) {
      const vm = this;
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          vm.loading = true;
          const shopId = vm.shopInfo.id;
          const { product, map, address, cellphone, companyName, contact, telephone } = vm.step1Form;
          const { province, city, district, lat, lng } = map;
          const { code, license, legal, idcard, idPic1, idPic2 } = vm.step2Form;
          const addr = address.split(district)[1];
          authCredit({
            shopId,
            idcard,
            product,
            contact,
            code,
            license,
            legal,
            telephone,
            front: idPic1,
            verso: idPic2,
            name: companyName,
            phone: cellphone,
            address: `${province}/${city}/${district}/${addr}`,
            coordinate: `${lat}-${lng}`
          }).then(res => {
            vm.loading = false;
            vm.step = 2;
            this.$message({
              type: '提交成功'
            });
          }).catch(err => {
            vm.loading = false;
            console.log(err);
          });
        } else {
          vm.$message({
            message: '您填写的信息有错误，请检查',
            type: 'warning'
          });
        }
      });
    },
    getAuthCredit() {
      const shopId = this.shopInfo.id;
      new Promise((resolve, reject) => {
        getAuthCredit({ shopId }).then(res => {
          const { data } = res;
          if (data) {
            if (data.status === '00100001') {
              this.step = 2;
            }
            this.details = data;
            this.srcList = [data.license, data.front, data.verso];
          }
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    toStep2(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.step = 1;
        } else {
          this.$message({
            message: '您填写的信息有错误，请检查',
            type: 'warning'
          });
          return false;
        }
      });
    },
    toStep1() {
      this.step = 0;
    },
    licencesSuc(res) {
      this.step2Form.license = res;
    },
    idPic1Suc(res) {
      this.step2Form.idPic1 = res;
    },
    idPic2Suc(res) {
      this.step2Form.idPic2 = res;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/shop-auth.scss";
.box{
  .details{
    min-width: 40%;
  }
}
</style>
